import { reqCartlist,reqCartadd,reqCartdelete} from "../../request/api";
//初始值
const initState = {
  //初始化数据
  //购物车列表
  cartlist:[],
  //购物车添加
  cartadd:[],
  //购物车删除
  cartdelete:[],
  //全选
//   allcheck:[]
};

//actionTypes
const types = {
  //修改数据 type
  CHANGE_CARTLIST: "SHOP_CHANGE_CARTLIST",
  CHANGE_CARTADD: "SHOP_CHANGE_CARTADD",
  CHANGE_CARTDELETE: "SHOP_CHANGE_CARTDELETE",
//   CHANGE_ALLCHECK: "SHOP_CHANGE_ALLCHECK",
 
};

//reducer 修改数据
const reducer = (state = initState, action) => {
  switch (action.type) {
    case types.CHANGE_CARTLIST:
      return {
        ...state,
        cartlist:action.cartlist,
      };
    case types.CHANGE_CARTADD:
        return {
          ...state,
          cartadd:action.cartadd,
        };
    case types.CHANGE_CARTDELETE:
            return {
              ...state,
              cartdelete:action.cartdelete,
            };
            // case types.CHANGE_ALLCHECK:
            //     return {
            //       ...state,
            //       cartdelete:action.cartdelete,
            //     };
    default:
      return state;
  }
};
//actionCreators组件派发的动作
export const actions = {
  changeCartlist: (cartlist) => ({ type: types.CHANGE_CARTLIST, cartlist}),
  changeCartadd: (cartadd) => ({ type: types.CHANGE_CARTADD, cartadd}),
  changeCartdelete: (cartdelete) => ({ type: types.CHANGE_CARTDELETE, cartdelete}),
  
  //请求 异步操作
  //购物车列表
  reqCartlist: () => (dispatch, getState) => {
      let uid=JSON.parse(sessionStorage.getItem('info')).uid
    reqCartlist({uid:uid}).then((res) => {
        if(res.data.code===200){
             //存信息
          dispatch(actions.changeCartlist(res.data.list))
        }
    });
  },
  //购物车添加
  reqCartadd: (goodsid) => (dispatch, getState) => {
    let uid=JSON.parse(sessionStorage.getItem('info')).uid;

    reqCartadd({uid:uid,goodsid:goodsid,type:1,num:1}).then((res) => {
      if(res.data.code===200){
           //存信息
        dispatch(actions.changeCartadd(res.data.list))
        dispatch(actions.reqCartlist())
      }
  });
},
//购物车删除
reqCartdelete: (id) => (dispatch, getState) => {
  
    reqCartdelete({id:id}).then((res) => {
      if(res.data.code===200){
           //存信息
        dispatch(actions.changeCartdelete(res.data.list))
        dispatch(actions.reqCartlist())
      }
  });
},
  
};

//selectors导出数据
export const getCartlist = state => state.shop.cartlist;
export const getCartadd = state => state.shop.cartadd;
export const getCartdelete = state => state.shop.cartdelete;

export default reducer;
